package com.bookshop.service.impl;

import com.bookshop.dao.BookDao;
import com.bookshop.dao.CategoryDao;
import com.bookshop.dao.impl.BookDaoImpl;
import com.bookshop.dao.impl.CategoryDaoImpl;
import com.bookshop.service.CategoryService;
import com.bookshop.utils.DataBaseUtil;

import java.sql.Connection;
import java.sql.SQLException;

public class CategoryServiceImpl implements CategoryService {
    @Override
    public int deleteById(Integer id) {
        int result = 0;//默认失败0行受影响
        Connection connection = null;
        try {
            connection = DataBaseUtil.getConnection();
            connection.setAutoCommit(false);//设置自动提交关闭
            //1.删除该类型下的所有图书
            BookDao bookDao = new BookDaoImpl(connection);
            bookDao.deleteByCId(id);
            //2.删除图书类型
            CategoryDao dao = new CategoryDaoImpl(connection);
            //模拟错误
            //int r=result/0;
            result = dao.deleteById(id);
            System.out.println("=======>"+result);
            //提交事务
            connection.commit();
        } catch (Exception e) {
            try {
                result = -1;
                connection.rollback();//异常时，回滚事务
            } catch (Exception ex) {
            }
        } finally {
            //关闭资源
            DataBaseUtil.closeAll(connection, null, null);
        }
        return result;
    }
}
